import 'package:flutter/material.dart';
import 'package:qunaimedical/components/comment_bar.dart';
import 'package:qunaimedical/components/item_comment.dart';
import 'package:qunaimedical/components/item_moment.dart';
import 'package:qunaimedical/components/primary_label.dart';
import 'package:qunaimedical/models/comment.dart';
import 'package:qunaimedical/models/list_response.dart';
import 'package:qunaimedical/models/map_response.dart';
import 'package:qunaimedical/models/moment.dart';
import 'package:qunaimedical/network/http.dart';
import 'package:qunaimedical/pages/comment_page.dart';
import 'package:qunaimedical/utils/common_util.dart';
import 'package:qunaimedical/utils/dialog_utils.dart';
import 'package:qunaimedical/utils/sp_utils.dart';
import 'package:qunaimedical/utils/toast_util.dart';
import 'package:qunaimedical/values/urls.dart';
import 'package:sprintf/sprintf.dart';

/// 帖子详情
class MomentDetailPage extends StatefulWidget {
  final Moment item;

  const MomentDetailPage({Key key, @required this.item}) : super(key: key);

  @override
  _MomentDetailPageState createState() => _MomentDetailPageState();
}

class _MomentDetailPageState extends State<MomentDetailPage> {
  TextEditingController _commentController = TextEditingController();

  /// 评论列表
  List<Comment> _comments = [];

  @override
  void initState() {
    super.initState();
    _getCommentList();
  }

  @override
  void dispose() {
    _commentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('帖子详情'),
        actions: [
          Offstage(
            offstage: widget.item.createdBy != SPUtils.getUser().id,
            child: IconButton(
                onPressed: () {
                  DialogUtils.showAlertDialog(context, '提示', '确认删除这个帖子？',
                      onPressed: () {
                    Navigator.pop(context);
                    _deletePost();
                  });
                },
                icon: Icon(
                  Icons.delete_forever,
                  color: Colors.grey[700],
                )),
          )
        ],
      ),
      body: Column(
        children: [
          Expanded(
            child: CustomScrollView(
              slivers: [
                _buildHeader(),
                _buildCommentList(),
              ],
            ),
          ),
          CommentBar(
            controller: _commentController,
            onSendPressed: _comment,
          )
        ],
      ),
    );
  }

  Widget _buildHeader() {
    return SliverToBoxAdapter(
      child: Column(
        children: [
          ItemMoment(widget.item),
          PrimaryLabel('评论'),
        ],
      ),
    );
  }

  /// 评论列表
  Widget _buildCommentList() {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (c, i) => ItemComment(
          _comments[i],
          onDelete: () {
            DialogUtils.showAlertDialog(
              context,
              '提示',
              '确认删除这条评论？',
              onPressed: () {
                Navigator.pop(context);
                _delete(i);
              },
            );
          },
          onReply: () {
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (c) => CommentPage(item: _comments[i]))).then(
              (value) {
                if (value != null && value) {
                  _getCommentList();
                }
              },
            );
          },
        ),
        childCount: _comments.length,
      ),
    );
  }

  void _getCommentList() async {
    var data = await XHttp.postJson(Urls.COMMENT_LIST, {
      "pageNo": 1, // 起始页（必填）
      "pageSize": 1000, // 分页大小（必填）
      "timelyConsultationId": widget.item.id, // 预约单ID/咨询单ID（必填）
      "doctorId": "" // 暂传空字符串（必填）
    });
    if (data != null && mounted) {
      ListResponse response = ListResponse.fromJson(data);
      if (response.code == 1) {
        setState(() {
          _comments = List.from(response.data.map((e) => Comment.fromJson(e)));
        });
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  /// 创建评论
  void _comment() async {
    CommonUtils.hideKeyboard(context);
    String content = _commentController.text.trim();
    if (SPUtils.getUser() == null) {
      DialogUtils.showAlertDialog(context, '提示', '请先进行登录');
      return;
    }
    if (content.isEmpty) {
      ToastUtil.show('评论内容不能为空', context);
      return;
    }
    DialogUtils.showWaitDialog(context);
    var data = await XHttp.postJson(Urls.COMMENT_ADD, {
      "timelyConsultationId": widget.item.id, // 所评论预约单ID
      "content": content, // 评论内容
      "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
    });
    Navigator.pop(context);
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 200) {
        _commentController.clear();
        _getCommentList();
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  /// 删除评论
  void _delete(int index) async {
    DialogUtils.showWaitDialog(context);
    // 判断是评论还是回复
    var data;
    if (_comments[index].byRepliedId == null) {
      // 删除评论
      data = await XHttp.postJson(Urls.COMMENT_REMOVE, {
        "id": _comments[index].id, // 评论ID
        "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
      });
    } else {
      // 删除回复
      data = await XHttp.postJson(Urls.REPLY_REMOVE, {
        "id": _comments[index].id, // 回复ID
        "commentId": _comments[index].commentId, // 评论ID
        "repliedId": SPUtils.getUser().id // 评论人ID，即当前登录人ID
      });
    }
    Navigator.pop(context);
    if (data != null) {
      MapResponse response = MapResponse.fromJson(data);
      if (response.code == 200) {
        setState(() {
          _comments.removeAt(index);
        });
      } else {
        ToastUtil.show(response.msg, context);
      }
    }
  }

  /// 删除帖子
  void _deletePost() async {
    DialogUtils.showWaitDialog(context);
    await XHttp.delete(sprintf(Urls.moment_delete, [widget.item.id]));
    Navigator.pop(context);
    Navigator.pop(context, true);
  }
}
